#!/usr/bin/perl -w
use strict;

###########################
#This module takes a VCF file containing the data from the other modules and links that data to drugs. 
#The first level of output links to NCI Match clinical trial
#The second level of output links to Drugs and targets from the DsigDB database
###########################


my $final_output = $ARGV[0];

my @sites;
open INFILE16, "/mnt/ilustre/app/medical/.data/impact/dsig_hyper.txt" or die "couldn't open dsig_hyper.txtn";
while (<INFILE16>)
        {
	chomp;
	push (@sites, $_);
        }
close INFILE16;


#############
#Module4
#Link to Actionable Therapeutics
#############

my $title = "drug_prediction.txt";	
open OUTFILE3, ">", "$title" or die "couldn't open $title\n";
my $title2 = "drug_prediction.html";	
open HTMLOUT, ">", "$title2" or die "couldn't open $title\n";

##########################
#Level 1 Output NCI MATCH
#########################
#Dabrafenib and Trametinib	BRAF	V600E	V600K
#Trametinib	BRAF
#AZD9291	EGFR 	T790M
#Afatinib	EGFR
#Afatinib	HER2
#Sunitinib	KIT
##SNPS first, then copynumber

my $braf_counter = 0;
print OUTFILE3 "\n
------------------------------------------------------------------------------\n
LEVEL 1: Actionable Therapeutics \n
------------------------------------------------------------------------------\n\n";
print OUTFILE3 "\nNCI Match Clinical Trials\n";
print OUTFILE3 "Mutation					Actionable Therapeutic(s)\n";
print OUTFILE3 "--------					-------------------------\n";

print HTMLOUT "<html><head>
<title>IMPACT OUTPUT</title></head>
<body>\n<center><h1>
IMPACT Drug Prediction Analysis <p>
</center></h1>
<br><p><hr><br><p><p><h2>LEVEL 1: Actionable Therapeutics</p></h2>\n<p>NCI Match Clinical Trials</p>\n<table border=\"1\" style=\"width:100%\">\n";
print HTMLOUT "<tr><td><b><center>GENE</td><td><b><center>VARIANT</td><td><b><center>ACTIONABLE THERAPEUTIC(S)</td></tr>\n"; 

my $BRAF = "\"\\bBRAF\\b\"";
my $EGFR = "\"\\bEGFR\\b\"";
my $HER2 = "\"\\bHER2\\b\"";
my $KIT = "\"\\bKIT\\b\"";
my $NF2 = "\"\\bNF2\\b\"";

my $braf_v600e = `grep $BRAF $final_output | grep V600E`;
if ($braf_v600e)
	{
	print OUTFILE3 "\tBRAF	V600E					Dabrafenib and Trametinib\n";
	$braf_counter++;
	print HTMLOUT "<tr><td>BRAF</td><td>V600E</td><td><a href= \"http://tanlab.ucdenver.edu/DSigDB/DSigDBv1.0/displayDrug.py?db=d1&id=1193\"> Dabrafenib</a> and <a href =\"http://tanlab.ucdenver.edu/DSigDB/DSigDBv1.0/displayDrug.py?db=d1&id=1129\"> Trametinib </a></td></tr>\n"; 



	}
my $braf_v600k = `grep $BRAF $final_output | grep V600K`;
if ($braf_v600k)
	{
	print OUTFILE3 "\tBRAF	V600K					Dabrafenib and Trametinib\n";
	print HTMLOUT "<tr><td>BRAF</td><td>V600K</td><td><a href= \"http://tanlab.ucdenver.edu/DSigDB/DSigDBv1.0/displayDrug.py?db=d1&id=1193\"> Dabrafenib</a> and <a href =\"http://tanlab.ucdenver.edu/DSigDB/DSigDBv1.0/displayDrug.py?db=d1&id=1129\"> Trametinib </a></td></tr>\n"; 

	$braf_counter++;
	}
if($braf_counter==0)	
	{
	my $braf_del = `grep $BRAF $final_output`;
	if ($braf_del)
        	{
		print OUTFILE3 "\tBRAF	Deleterious				Trametinib\n";
		print HTMLOUT "<tr><td>BRAF</td><td>deleterious</td><td><a href=\"http://tanlab.ucdenver.edu/DSigDB/DSigDBv1.0/displayDrug.py?db=d1&id=1129\">Trametinib</a></td></tr>\n"; 
		}
	}
my $egfr_counter = 0;
my $egfr_t790m = `grep $EGFR $final_output | grep T790M`;
if ($egfr_t790m)
        {
	print OUTFILE3 "\tEGFR    T790M					AZD9291\n";
	print HTMLOUT "<tr><td>EGFR</td><td>T790M</td><td>AZD9291</td></tr>\n"; 
        $egfr_counter++;
	}

open EG, ">", "EGFR.txt" or die "couldn't open EGFR\n";
my $egfr_del = `grep $EGFR $final_output`;
print EG "$egfr_del\n";
close EG; 

open INFILE17, "EGFR.txt" or die "couldn't open EG.txt\n";
while (<INFILE17>)
        {
	chomp;
	#print $_; 	
        if ($_ =~ /:p.(\w+\d+\w+)\s+/)
                	{
			my $mut = $1;
                	print OUTFILE3 "\tEGFR    $mut	Deleterious				Afatinib\n";
			print HTMLOUT "<tr><td>EGFR</td><td>$mut</td><td><a href= \"http://tanlab.ucdenver.edu/DSigDB/DSigDBv1.0/displayDrug.py?db=d1&id=1112\">Afatinib</a></td></tr>\n"; 
                	}
		}
close INFILE17; 

my $her2 = `grep $HER2 $final_output| grep SNV `;
if ($her2 =~ /:p.(\D+\d+\D+)\s+/)
        {
	my $mut = $1;
	print OUTFILE3 "\tHER2	$mut	Deleterious			Afatinib\n";
	print HTMLOUT "<tr><td>HER2</td><td>$mut</td><td><a href= \"http://tanlab.ucdenver.edu/DSigDB/DSigDBv1.0/displayDrug.py?db=d1&id=1112\">Afatinib</a></td></tr>\n"; 
	}
my $kit = `grep $KIT $final_output `;
if ($kit =~ /:p.(\D+\d+\D+)\s+/)
        {
	my $mut = $1;
	print OUTFILE3 "\tKIT	$mut	Deleterious			Sunitinib\n";
	print HTMLOUT "<tr><td>KIT</td><td>$mut</td><td><a href= \"http://tanlab.ucdenver.edu/DSigDB/DSigDBv1.0/displayDrug.py?db=d1&id=1006\">Sunitinib</a></td></tr>\n"; 
	}

#####copy number alteration
#Ado-trastuzumab_emtansine	HER2 amplification
#VS6063	NF2 deletion

my $her2_amp = `grep $HER2 $final_output | grep AMP `;
if ($her2_amp)
        {
	my $mut = $1;
        print OUTFILE3 "\tHER2	AMPLIFICATION				Ado-trastuzumab_emtansine\n";
	print HTMLOUT "<tr><td>HER2</td><td>AMPLIFICATION</td><td>Ado-trastuzumab_emtansine</td></tr>\n"; 
        }
my $NF2_del = `grep $NF2 $final_output | grep DEL `;
if ($NF2_del)
        {
	my $mut = $1;
        print OUTFILE3 "\tNF2	DELETION				VS6063\n";
	print HTMLOUT "<tr><td>NF2</td><td>DELETIONt</td><td>VS6063</td></tr>\n"; 
        }
        print HTMLOUT "</table>\n";
        
print OUTFILE3 "\nMD Anderson Personalized Cancer Therapy\n";
print OUTFILE3 "Mutation					Actionable Therapeutic(s)\n";
print OUTFILE3 "--------					-------------------------\n";
	
print HTMLOUT "<p>MD Anderson Personalized Cancer Therapy</p>\n<table border=\"1\" style=\"width:100%\">\n";
print HTMLOUT "<tr><td><b><center>GENE</td><td><b><center>VARIANT</td><td><b><center>ACTIONABLE THERAPEUTIC(S)</td></tr>\n"; 


my %mda; 
open INFILE14, "/mnt/ilustre/app/medical/.data/impact/MDA.txt" or die "couldn't open MDA.txt\n";
while (<INFILE14>)
        {
	chomp;
	my @info = split(',', $_);	
	my $gene = shift @info;
	my $string; 
	foreach(@info)
		{
		if ($string)
			{
			$string = "$string".",$_";
			}
		else
			{
			$string = $_;
			}
		}
	$mda{$gene} = $string;	
	}

while ( my ($key, $value) = each(%mda) ) 
	{
	my $grep = "\"\\b$key\\b\"";
	my $get_grep = `grep $grep $final_output `;

	open KEY, ">", "$key.txt" or die "couldn't open $key.txt\n";
	print KEY "$get_grep\n";
	close KEY;

	open INFILE18, "$key.txt" or die "couldn't open $key.txt\n";
	while (<INFILE18>)
        	{
		chomp;
		#print $_;
        	if ($_ =~ /:p.(\w+\d+\w+)\s+/)
                        {
			my $mut = $1;
        		print OUTFILE3 "\t$key\t$mut\t\t\t$value\n";
			print HTMLOUT "<tr><td>$key</td><td>$mut</td><td>\n"; 
			my @info = split(',', $value);
			foreach(@info)
				{
				my $cur_drug = $_;
				my $match = 0;
				foreach(@sites)
					{
					my @info2 = split('\t', $_);
					chomp $info[0];
					if ("$cur_drug" eq "$info2[0]")
						{
						print HTMLOUT "<a href=\"$info2[1]\">$cur_drug </a>";
						$match =1;
						}
					}
				if($match == 0)
					{
					print HTMLOUT "$cur_drug ";
					}
				}
        		print HTMLOUT "</td></tr>\n";
                        }
                }
	close INFILE18;
	}

print OUTFILE3 "\nDsigDB  FDA approved Kinase Inhibitors\n";
print OUTFILE3 "Mutation					Actionable Therapeutic(s)\n";
print OUTFILE3 "--------					-------------------------\n";
        print HTMLOUT "</table>\n";

print HTMLOUT "<p>DSigDB FDA Approved Kinase Inhibitors</p>\n<table border=\"1\" style=\"width:100%\">\n";
print HTMLOUT "<tr><td><b><center>GENE</td><td><b><center>VARIANT</td><td><b><center>ACTIONABLE THERAPEUTIC(S)</td></tr>\n"; 

my %keio; 
open INFILE14, "/mnt/ilustre/app/medical/.data/impact/kieo.txt" or die "couldn't open keio.txt\n";
while (<INFILE14>)
        {
	chomp;
	my @info = split(',', $_);	
	my $gene = shift @info;
	my $string; 
	foreach(@info)
		{
		if ($string)
			{
			$string = "$string".",$_";
			}
		else
			{
			$string = $_;
			}
		}
	$keio{$gene} = $string;	
	}


while ( my ($key, $value) = each(%keio) )
        {
	my $key_held = 0; 
	if ($key =~ /(.*)\/(.*)/)
		{
		$key_held =  "$1_$2\n";
		#print "$key\n";
		}
	my $grep = "\"\\b$key\\b\"";
        my $get_grep = `grep $grep $final_output `;

        open KEY, ">", "$key_held.txt" or die "couldn't open $key_held.txt\n";
        print KEY "$get_grep\n";
        close KEY;

        open INFILE18, "$key_held.txt" or die "couldn't open $key_held.txt\n";
        while (<INFILE18>)
                {
                chomp;
                #print $_;
                if ($_ =~ /:p.(\w+\d+\w+)\s+/)
                        {
			my $mut = $1;
        		print OUTFILE3 "\t$key\t$mut\t\t\t$value\n";
			print HTMLOUT "<tr><td>$key</td><td>$mut</td><td>\n"; 
			my @info = split(',', $value);
			foreach(@info)
				{
				my $cur_drug = $_;
				my $match = 0;
				foreach(@sites)
					{
					my @info2 = split('\t', $_);
					if ("$cur_drug" eq "$info2[0]")
						{
						print HTMLOUT "<a href=\"$info2[1]\">$cur_drug </a>";
						$match =1;
						}
					}
				if($match == 0)
					{
					print HTMLOUT "$cur_drug ";
					}
				}
        		print HTMLOUT "</tzd></tr>\n";
                        }
                }
        close INFILE18;
        }

        print HTMLOUT "</table>\n";

####################
#Level 2 Output
####################

print OUTFILE3 "\n
------------------------------------------------------------------------------\n
LEVEL 2 Actionable Therapeutics from DsigDB Database \n
------------------------------------------------------------------------------\n\n";

print HTMLOUT "<p></p><p><h2>LEVEL 2: Actionable Therapeutics from DSigDB</p></h2>\n<table border=\"1\" style=\"width:100%\">\n";


my @genes; 

#cut -f 7 TCGA_C_4494.final_delet_muts.txt | sort | uniq |
my $mod_4_input = "delt_genes.txt";
my $ee = system("cut -f 7 $final_output | sort | uniq > $mod_4_input");
open INFILE11, "$mod_4_input" or die "couldn't open $mod_4_input\n";
while(<INFILE11>)
        {
        chomp;
	push @genes, "$_";
        }
close INFILE11;

my $len = scalar @genes; 
print OUTFILE3 "Potential Gene Targets($len):\n@genes\n\n";
print HTMLOUT "<p>Potential Gene Targets($len):\n@genes</p>";


my @D1_genes; 

open INFILE8, "/mnt/ilustre/app/medical/.data/impact/D1_geneList.txt" or die "couldn't open D1_geneList.txt\n";
while(<INFILE8>)
        {
	chomp;
	my $d1 = $_; 
	foreach (@genes)
		{
		if ("$_" eq "$d1")
			{
			#print "$_ is on D1 $d1\n";  
			push @D1_genes, "$_"; 
			}
		}
	}
close INFILE8; 

@genes = @D1_genes; 

my %drugs;
my @drug_array;
open INFILE10, "/mnt/ilustre/app/medical/.data/impact/DSigDB_D1_data_set.txt" or die "couldn't open DSigDB_D1_data_set.txt\n";
while(<INFILE10>)
	{
	chomp;
	my @targets = split('\t', $_);	
	my $name_drug = shift @targets;
	my $site = shift @targets;
	foreach(@genes) 
		{
		my $gene = $_;
		#only push onto the hofAs if in the gene list
		if ( grep { $_ eq $gene} @targets )
			{
			#print "MATCHES $_ \t $gene \n"; 
			$drugs{$name_drug} = [@targets];
			}
		}
	}
close INFILE10;

my @list_drugs;
my @gene_list; 
my @matches;
foreach my $family ( keys %drugs )
	{
	#print "$family: @{ $drugs{$family} }\n";
	push @list_drugs, $family;
	push @gene_list, @{ $drugs{$family} };
	}
my @unique = uniq( @gene_list );
print "@list_drugs\n@unique\n";

#print "\t";
foreach(@unique)
	{
	#print "$_\t";
	}
#print "\n";
print HTMLOUT "<tr><td><b><center>DRUG</td><td><b><center>TARGETS HIT</td><td><b><center>POTENTIAL TARGETS</td><td><b><center>P-value (hypergeometric test)</td><td><b><center>P-value (Permutation test)</td></tr>\n"; 
print OUTFILE3 "Drug\t\t\tTargets Hit\t\tPotential Targets\tP-value (hypergeometric test)\tP-value (Permutation test)\n";
open OUTFILE2, ">", "druglist.txt" or die "couldn't open druglist.txt\n";

foreach my $family ( keys %drugs )
	{
	#my $get_line = "$family\t";
	#print "$family\t";
	my $one_counts = 0;
	my $two_counts = 0;
	my $zero_counts = 0; 

	foreach(@unique)
		{
		my $flag1 = 0; 
		my $fg2 = 0; 
		my $match1 = $_;
		#print "$match1\n";
		foreach(@{ $drugs{$family} })
 			{
			my $match2 = $_;
			#print "$match2\n";
			if ("$match1" eq "$match2")
				{
				$flag1 = 1;
				foreach(@genes)
					{
					my $match3 = $_;
		                        if ("$match3" eq "$match2")
                                		{
                     		        	$flag1 = 2;
						}
					}
				#print "2\t";
				}
			}
		if ($flag1 == 1)
			{
			#print "1\t";	
			$one_counts++;
			}
	        if ($flag1 == 2)
        	        {
                	#print "2\t";
			$two_counts++;
                	}
	        if ($flag1 == 0)
        	        {
                	#print "0\t";
			$zero_counts++;
                	}
		}
	#print "\t";
	#print "$one_counts\t$two_counts\t$zero_counts\n";
	#phyperscript
	#x, q vector of quantiles representing the number of white balls drawn  without replacement from an urn which contains both black and white balls.
	#m the number of white balls in the urn.
	#n the number of black balls in the urn.
	#k the number of balls drawn from the urn.
	my $gene_target_for_drug = $two_counts + $one_counts;
	my $x = $two_counts;
	my $m = $gene_target_for_drug;
	my $n = (1288-$gene_target_for_drug);
	my $k = @genes;
	#print "\t$x\t$m\t$n\t$k\t";
	#$get_line = "$family\t"."\t$x\t$m\t$n\t$k\t";
	push @matches,"$x\t$k\t$m";

		print OUTFILE2 "$family\t\t$x\t$m\t\n";

	}

open OUTFILE1, ">", "hyperTest.txt" or die "couldn't open hyperTest.txt\n";
	foreach(@matches)
		{
		print OUTFILE1 "$_\n";
		}
close OUTFILE1;
close OUTFILE2;
close OUTFILE3;

sub uniq {
  my %seen;
  return grep { !$seen{$_}++ } @_;
}

my @gene; 
open INFILE14, "druglist.txt" or die "couldn't open druglist.txt\n";
while (<INFILE14>)
        {
	chomp;
	push (@gene, $ _);
	}

my @nci; 
open INFILE44, "/mnt/ilustre/app/medical/.data/impact/druglist2.txt" or die "couldn't open druglist.txt\n";
while (<INFILE44>)
        {
	chomp;
	push (@nci, $ _);
	}

foreach(@gene)
	{
#	print "$_\n";
	}	
my @p; 
my @p2;
open INFILE15, "p_values.txt" or die "couldn't open p_values.txt\n";
while (<INFILE15>)
        {
	chomp;
	my @info = split("\t", $_);
	push (@p, $info[-1]);	
	push (@p2, $info[-2]);	
	}
close INFILE14; 
close INFILE15; 

my @sites; 
open INFILE16, "/mnt/ilustre/app/medical/.data/impact/dsig_hyper.txt" or die "couldn't open dsig_hyper.txtn";
while (<INFILE16>)
        {
	chomp;
	push (@sites, $_);	
	}
close INFILE16; 


my $amount = @gene; 
my $amount2 = @p; 
#print "$amount\t$amount2\n";
my $count = 0; 
my $top = shift @p;
my $top2 = shift @p2;
my %output; 

while ($count < $amount)
	{
	my $one = shift @gene;
	my $three = shift @p2;
	my $three2 = sprintf "%.3f", $three;
	my $combo = "$one"."\t$three2";
	my $two = shift @p;
	$output{$combo} = $two;
	$count++
	}

while ( my ($key, $value) = each(%output) ) {
        #print "$key \t\tHEY\t\t $value\n";
    }

my $title = "drug_prediction.txt";
open OUTFILE3, ">>", "$title" or die "couldn't open $title\n";
my $title2 = "drug_prediction.html";
open HTMLOUT, ">>", "$title2" or die "couldn't open $title\n";
my $output_count = 0;
foreach my $name (sort { $output{$a} <=> $output{$b}or $b cmp $a } keys %output) 
	{
	foreach(@nci)
		{
		my $nci_drug = $_; 
		if ($name =~ /$nci_drug/)
			{
			printf OUTFILE3 "%-8s %s\n", $name, $output{$name};
			if($name =~/(\D+)\s+(\S+)\s+(\S+)\s+(\S+)/)
				{
				my $website; 
				foreach(@sites)
					{
					my @info2 = split("\t", $_);
					my $drug_web = $info2[0]; 
					#print "drug_web
					if ("$drug_web" eq "$nci_drug")
						{
						$website = $info2[1];
					 	}
					}
				print "$1\t$2\t$3\t$4\t$output{$name}\n";
				print HTMLOUT "<tr><td><a href=\"$website\">$1</a></td><td>$2</td><td>$3</td><td>$4</td><td>$output{$name}</td></tr>\n";
				}
			}
		}
	$output_count++;
	}
 print HTMLOUT "</table>\n";
close OUTFILE3; 
close HTMLOUT; 
